package net.ccfish.jvue.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.github.pagehelper.PageHelper;

import net.ccfish.common.OrderByUtils;
import net.ccfish.common.mybatis.BaseMapper;
import net.ccfish.common.web.PageParam;
import net.ccfish.jvue.autogen.dao.JvueUserMapper;
import net.ccfish.jvue.autogen.dao.JvueUserRoleMapper;
import net.ccfish.jvue.autogen.model.JvueUser;
import net.ccfish.jvue.autogen.model.JvueUserRole;
import net.ccfish.jvue.domain.dao.JvueExUserMapper;
import net.ccfish.jvue.domain.model.JvueExUser;
import net.ccfish.jvue.service.JvueUserService;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;


/**
 * Generated by Spring Data Generator on 31/01/2018
 */
@Service
@Transactional
public class JvueUserServiceImpl implements JvueUserService {

    private JvueUserMapper userMapper;
    
    @Autowired
    private JvueExUserMapper exUserMapper;
    @Autowired
    private JvueUserRoleMapper userRoleMapper;

    @Autowired
    public JvueUserServiceImpl(JvueUserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public BaseMapper<JvueUser> baseMapper() {
        return this.userMapper;
    }
    
    @Override
    @CacheEvict(value = "JwtUserDetailsService", key = "#result.username")
    public JvueUser updateRoles(Long id, List<Integer> roles) {
        Assert.notNull(id, "用户ID不能为空");
        JvueUserRole userRole = new JvueUserRole();
        userRole.setUserId(id);
        List<JvueUserRole> userRoles = userRoleMapper.select(userRole);
        
        Collection<Integer> deleds;
        Collection<Integer> addeds;
        
        List<Integer> existes = userRoles.stream().map(r -> r.getRoleId()).collect(Collectors.toList());
        
        if (existes != null) {
            if (roles != null && roles.size() > 0) {
                deleds = CollectionUtils.subtract(existes, roles);
                addeds = CollectionUtils.subtract(roles, existes);
            } else {
                // 删除所有
                userRoleMapper.delete(userRole);
                deleds = null;
                addeds = null;
            }
        } else {
            deleds = null;
            addeds = roles;
        }
        
        if (deleds != null && deleds.size() > 0) {
//            SearchCriteria<UserRole> searchCriteria = new SearchCriteria<>();
//            searchCriteria.add(JpaRestrictions.eq("userId", id, false));
//            searchCriteria.add(JpaRestrictions.in("roleId", deleds, false));
//            List<UserRole> dRoles = userRoleMapper.findAll(searchCriteria);
//            userRoleMapper.deleteAll(dRoles);
            
            Example example = new Example.Builder(JvueUserRole.class).where(
                    WeekendSqls.<JvueUserRole>custom().andEqualTo(JvueUserRole::getUserId, id).andIn(JvueUserRole::getRoleId, deleds))
                    .build();
            
            userRoleMapper.deleteByExample(example);
        }
        
        if (addeds != null && addeds.size() > 0) {
            
            for (Integer roleId: addeds) {
                JvueUserRole role = new JvueUserRole();
                role.setUserId(id);
                role.setRoleId(roleId);
                userRoleMapper.insertSelective(role);
            }
        }
        
        return getOne(id);
    }

    @CacheEvict(value = "JwtUserDetailsService", key = "#result.username")
    @Override
    public JvueUser update(Long id, JvueUser data) {
        JvueUser jvueUser = userMapper.selectByPrimaryKey(id);
        if (jvueUser != null) {
            // jvueUser.setSuperUser(data.getSuperUser());
            jvueUser.setPassword(data.getPassword());
            jvueUser.setDeptCode(data.getDeptCode());
            jvueUser.setNickname(data.getNickname());
            jvueUser.setEmail(data.getEmail());
            jvueUser.setStatus(data.getStatus());
            userMapper.updateByPrimaryKeySelective(jvueUser);
            return jvueUser;
        } else {
            return data;
        }
    }
    
    @Override
    public void delete(Long id) {
    	userMapper.deleteByPrimaryKey(id);
    }
    
    @Override
    public List<JvueExUser> searchUser(PageParam pageParam) {
        String orderBy = OrderByUtils.toString(pageParam.getSort(), pageParam.getDirection());
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize(), orderBy);
        
        // TODO 后续追加查询条件
        return exUserMapper.searchUsers(null);
    }

}
